package com.cali.libcore.dialog.manager

import java.util.concurrent.ConcurrentLinkedQueue

/**
 * 支持多个Dialog依次弹出
 * Created by mq on 2018/9/1 下午4:35
 * mqcoder90@gmail.com
 */

class MyDialogsManager private constructor() {

    @Volatile
    private var showing = false//是否有dialog在展示
    private val dialogQueue = ConcurrentLinkedQueue<DialogWrapper>()

    object DialogHolder {
        val instance = MyDialogsManager()
    }

    /**
     * 请求加入队列并展示
     *
     * @param dialogWrapper DialogWrapper
     * @return 加入队列是否成功
     */
    @Synchronized
    fun requestShow(dialogWrapper: DialogWrapper): Boolean {
        val b = dialogQueue.offer(dialogWrapper)
        checkAndDispatch()
        return b
    }

    /**
     * 结束一次展示 并且检查下一个弹窗
     */
    @Synchronized
    fun over() {
        showing = false
        next()
    }

    @Synchronized
    private fun checkAndDispatch() {
        if (!showing) {
            next()
        }
    }

    /**
     * 弹出下一个弹窗
     */
    @Synchronized
    private operator fun next() {
        val poll = dialogQueue.poll() ?: return
        val dialog = poll.dialog
        if (dialog != null) {
            showing = true
            dialog.show()
        }
    }

    companion object {

        val instance: MyDialogsManager
            get() = DialogHolder.instance
    }


}
